import React, {useState} from 'react';
import {SubmitHandler, useForm} from 'react-hook-form';
import Button from "@/components/ui/Button/Button";
import styles from "./LoginForm.module.css";
import FormInput from "@/components/ui/Forms/FormElements/FormInput";
import {TypeLoginFormProps, TypeUser} from "@/shared/types";
import {handleLogin} from "@/lib/actions";
import {postObjWithoutToken} from "@/services/api_service";
import {useRouter} from "next/navigation";

export const emailPattern = {
    value: new RegExp('^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$', 'ig'),
    message: "Неверный формат электронной почты",
};

export default function LoginForm({setModalOpen, setCurrentAuthForm}: TypeLoginFormProps) {
    const {
        register,
        handleSubmit,
        formState: {errors},
    } = useForm<TypeUser>()
    const {replace} = useRouter();

    const [errorMessage, setErrorMessage] = useState<string | null>(null);
    const [errorKey, setErrorKey] = useState<number>(0);

    const onSubmit: SubmitHandler<TypeUser> = async (data: TypeUser) => {
        const response = await postObjWithoutToken('/api/auth/login/', JSON.stringify(data))
        console.log(response)
        if (response?.access) {
            await handleLogin(response.id, response.access, response.refresh);

            setModalOpen(false);
            setCurrentAuthForm("none");

            if (response.role === 'admin') {
                replace('/admin');
            } else {
                replace('/user');
            }

            setErrorMessage(null);
        } else {
            setErrorMessage('Неверный логин или пароль');
            setErrorKey(prev => prev + 1);
        }
    }

    return (
        <form onSubmit={handleSubmit(onSubmit)} className={styles.loginForm_container}>
            <FormInput<TypeUser>
                id="email"
                type="text"
                name="email"
                kind="email"
                autoComplete="email"
                label="Электронная почта"
                placeholder="ivanov@mail.com"
                register={register}
                rules={{
                    required: "Введите электронную почту",
                    pattern: emailPattern
                }}
                errors={errors}
            />

            <FormInput<TypeUser>
                id="password"
                type="password"
                name="password"
                kind="password"
                autoComplete="current-password"
                label="Пароль"
                placeholder="Пароль"
                register={register}
                rules={{
                    required: "Введите пароль",
                    minLength: {
                        value: 8,
                        message: "Длина пароля должна быть от 8 до 24 символов"
                    },
                    maxLength: {
                        value: 24,
                        message: "Длина пароля должна быть от 8 до 24 символов"
                    }
                }}
                errors={errors}
            />

            {errorMessage &&
                <div key={errorKey} className={styles.error_message}>
                    <p>{errorMessage}</p>
                </div>}

            <div className={styles.buttons_container}>
                <Button type="submit" kind="submit" content="Войти"/>
                <Button
                    type="button"
                    kind="secondary"
                    content="Создать аккаунт"
                    onClick={() => {
                        setModalOpen(false);
                        setCurrentAuthForm("registration");
                    }}
                />
            </div>
        </form>
    );
}
